package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.weixin.utils.PayCommonUtil;
import com.qy.base.utils.weixin.utils.WXAPPConfigUtil;
import com.qy.model.*;
import com.qy.service.MemberService;
import com.qy.service.MessageService;
import com.qy.service.RewardOrderService;
import com.github.pagehelper.PageHelper;
import com.qy.service.TollService;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.util.*;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("app/reward/order")
public class RewardOrderController {
    @Resource
    private RewardOrderService rewardOrderService;

    @Resource
    private TollService tollService;

    @Resource
    private MemberService memberService;

    @Resource
    private MessageService messageService;

    @PostMapping("/add")
    public Result add(@RequestBody RewardOrder rewardOrder) {
        rewardOrderService.save(rewardOrder);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        rewardOrderService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody RewardOrder rewardOrder) {
        rewardOrderService.update(rewardOrder);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        RewardOrder rewardOrder = rewardOrderService.findById(id);
        return ResultGenerator.successResult(rewardOrder);
    }

    @GetMapping("/list")
    public Result list(PageBean<RewardOrder> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<RewardOrder> list = rewardOrderService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //获取悬赏价格
    @GetMapping("/getRewardPrice")
    public Result getRewardPrice() {
        List<Toll> list = tollService.selectRewardPrice();

        return ResultGenerator.successResult(list);
    }

    //悬赏
    @PostMapping("/reward")
    public Result reward(@RequestBody RewardOrder rewardOrder) {
        if (rewardOrder.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member = memberService.findById(rewardOrder.getUser_id());
        if (rewardOrder.getNeed() == null || rewardOrder.getNeed().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }

        Random random = new Random();
        String content = String.valueOf(random.nextInt(9999) % (9999 - 1000 + 1) + 1000);
        String randomOrderNum = DateUtil.getNowTimestamp() + content;

        rewardOrder.setOrder_number(randomOrderNum);
        rewardOrder.setRewarder(member.getName());
        rewardOrder.setSubmit_time(DateUtil.getNowTimestamp());
        rewardOrderService.save(rewardOrder);
        return ResultGenerator.successResult(rewardOrder.getId());
    }

    //悬赏支付
    @PostMapping("/rewardPay")
    public Result reward(@RequestBody RewardOrder rewardOrder, HttpServletRequest request) throws Exception {
        if (rewardOrder.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        RewardOrder rewardOrder1 = rewardOrderService.findById(rewardOrder.getId());
        Member member = memberService.findById(rewardOrder1.getUser_id());

        //准备商家数据包
        HashMap<String, Object> attachMap = new HashMap<>();
        attachMap.put("id", rewardOrder1.getId());
        SortedMap<Object, Object> resultMap = PayCommonUtil.wxPay(WXAPPConfigUtil.APPID, WXAPPConfigUtil.MCH_ID, rewardOrder1.getOrder_number(), Double.valueOf(rewardOrder1.getAmount()), member.getWechat_id(), "悬赏", "JSAPI", "", JSONObject.fromObject(attachMap).toString(), WXAPPConfigUtil.REWARD_PAY_NOTIFY_URL, request);

        return ResultGenerator.successResult(resultMap);
    }

    //悬赏支付回调
    @RequestMapping("/rewardPayNotify")
    public void rewardPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map packageParams = PayCommonUtil.getWXNotifyData(request, WXAPPConfigUtil.API_KEY);
        String resXml = "";
        if (packageParams != null) {
            //------------------------------
            //处理业务开始
            //------------------------------

            FileWriter writer = new FileWriter(Constants.PATH_IMAGE_PATH + "wx_notify.txt", true);

            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                // 这里是支付成功
                //////////执行自己的业务逻辑////////////////

                try {
//                    Double money = Double.valueOf((String) packageParams.get("total_fee")) / 100;
//                    String randomOrderNum = (String) packageParams.get("out_trade_no");
                    String attach = (String) packageParams.get("attach");
                    JSONObject attachObj = JSONObject.fromObject(attach);
                    String id = attachObj.getString("id");

                    RewardOrder rewardOrder = rewardOrderService.findById(Integer.valueOf(id));
                    rewardOrder.setOrder_state(2);
                    rewardOrder.setPay_time(DateUtil.getNowTimestamp());
                    rewardOrderService.update(rewardOrder);

                    Member member = memberService.findById(rewardOrder.getUser_id());

                    Message message = new Message();
                    message.setMessage_type(2);
                    message.setMessage_content(member.getNickname() + "发起了悬赏");
                    message.setMessage_port(2);
                    message.setAdd_time(DateUtil.getNowTimestamp());
                    messageService.save(message);
                } catch (Exception e) {
                    writer.write(e.toString());
                    writer.flush();
                    writer.close();
                }

                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                resXml = PayCommonUtil.setXML("SUCCESS", "OK");

            } else {
                resXml = PayCommonUtil.setXML("FAIL", "报文为空");
            }
        } else {
            resXml = PayCommonUtil.setXML("FAIL", "报文为空");
        }
        //------------------------------
        //处理业务完毕
        //------------------------------
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    //我的悬赏
    @GetMapping("/myReward")
    public Result myReward(PageBean<RewardOrder> page, RewardOrder rewardOrder) {
        if (rewardOrder.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        PageHelper.startPage(page.getPageNum(), page.getSize(), "submit_time desc");
        List<RewardOrder> list = rewardOrderService.selectMyReward(rewardOrder);
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //悬赏详情
    @GetMapping("/rewardDetail")
    public Result rewardDetail(RewardOrder rewardOrder) {
        if (rewardOrder.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        RewardOrder rewardOrder1 = rewardOrderService.findById(rewardOrder.getId());
        return ResultGenerator.successResult(rewardOrder1);
    }

    //取消悬赏
    @PostMapping("/cancleReward")
    public Result cancleReward(@RequestBody RewardOrder rewardOrder) {
        if (rewardOrder.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        RewardOrder rewardOrder1 = rewardOrderService.findById(rewardOrder.getId());
        rewardOrder1.setOrder_state(3);
        rewardOrder1.setCancel_time(DateUtil.getNowTimestamp());
        rewardOrderService.update(rewardOrder1);
        return ResultGenerator.successResult(rewardOrder1);
    }

}
